﻿using llm_project.Models;
using System.Text;
using System.Text.RegularExpressions;

namespace llm_project.Infrastructure.Helpers
{
    public static class TagUtils
    {
        /// <summary>
        /// 构建单个用户的Prompt
        /// </summary>
        public static string BuildSinglePrompt(List<UserActionReq> actions)
        {
            var sb = new StringBuilder();
            foreach (var action in actions)
            {
                sb.AppendLine($"- Action: {action.Action}, Query: {action.Query}, ItemId: {action.ItemId}, Category: {action.Category}");
            }

            return $@"
你是电商用户行为分析师，根据以下行为生成不超过5个精准标签及权重（0.1~1.0），格式：
标签名,权重值
标签名,权重值

用户行为：
{sb}
";
        }

        /// <summary>
        /// 构建批量用户的Prompt
        /// </summary>
        public static string BuildBatchPrompt(List<UserBehaviorReq> userBehaviors)
        {
            var sb = new StringBuilder();
            sb.AppendLine("你是电商用户行为分析师，请根据以下用户行为生成标签。每个用户的格式：");
            sb.AppendLine("【用户ID: [用户ID]】");
            sb.AppendLine("标签1,权重值");
            sb.AppendLine("标签2,权重值");
            sb.AppendLine("---");
            sb.AppendLine("要求：1. 每个用户最多5个标签 2. 权重0.1~1.0 3. 标签不超过10字");
            sb.AppendLine("用户行为数据：");

            foreach (var user in userBehaviors)
            {
                sb.AppendLine($"用户 {user.UserId} 的行为：");
                user.Actions.ForEach(a =>
                    sb.AppendLine($"- Action: {a.Action}, Query: {a.Query}, ItemId: {a.ItemId}, Category: {a.Category}")
                );
                sb.AppendLine();
            }

            return sb.AppendLine("请严格按格式返回，不要添加解释。").ToString();
        }

        /// <summary>
        /// 解析单个用户的标签结果
        /// </summary>
        public static List<(string Label, double Weight)> ParseSingleTags(string rawOutput)
        {
            if (string.IsNullOrWhiteSpace(rawOutput))
                return new List<(string, double)>();

            var tags = new List<(string Label, double Weight)>();
            foreach (var line in rawOutput.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var parts = line.Split(',');
                if (parts.Length == 2 &&
                    double.TryParse(parts[1].Trim(), out double weight) &&
                    weight is >= 0.1 and <= 1.0)
                {
                    var label = parts[0].Trim();
                    if (label.Length <= 10)
                        tags.Add((label, weight));
                }
            }

            return tags.OrderByDescending(t => t.Weight).Take(5).ToList();
        }

        /// <summary>
        /// 解析批量用户的标签结果
        /// </summary>
        public static Dictionary<string, List<(string Label, double Weight)>> ParseBatchTags(string rawOutput, ILogger logger)
        {
            var result = new Dictionary<string, List<(string Label, double Weight)>>();
            if (string.IsNullOrWhiteSpace(rawOutput))
                return result;

            try
            {
                // 匹配所有用户块：【用户ID: xxx】...内容...
                var matches = Regex.Matches(rawOutput, @"【用户ID:\s*(\S+?)】([^【]*)");
                foreach (Match match in matches)
                {
                    var userId = match.Groups[1].Value.Trim();
                    var content = match.Groups[2].Value.Trim();
                    if (string.IsNullOrEmpty(userId))
                        continue;

                    var tags = ParseSingleTags(content);
                    if (tags.Any())
                        result[userId] = tags;
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "批量标签解析失败，原始内容：{RawOutput}", rawOutput);
            }

            return result;
        }
    }
}
